package com.yy.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yy.dao.TestUserDao;
import com.yy.enums.ResponseEnum;
import com.yy.pojo.TestUser;
import com.yy.service.Impl.TestUserServiceImpl;
import com.yy.service.TestUserService;
import com.yy.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author young
 * @date 2022/8/26 9:36
 * @description:
 */
@Slf4j
@RestController
@RequestMapping("/mysql")
public class TestUserController {
    private static final DateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private TestUserServiceImpl testUserService;
    @Autowired
    private TestUserDao Mapper;
    /*                                自主测试                              */
     @GetMapping("/test/{id}")
     public R<Boolean> test(@PathVariable Integer id){
         return R.ok(testUserService.tests(id));
}

    /**
     * 增加一个test用户
     *
     * @param testUser
     * @return
     */
    @PostMapping("/addOne")
    public R<Boolean> addUser(TestUser testUser) {
        boolean save = testUserService.save(testUser);
        return R.ok(save);
    }

    /**
     * 批量添加test用户
     *
     * @param
     * @return
     */
    @PostMapping("/addMore")
    public R<Boolean> addBatch() {
        List<TestUser> list = new ArrayList<>();
        TestUser user1 = new TestUser("黎治跃", true, "韩家墩五号", new Date());
        TestUser user2 = new TestUser("李帅", false, "李家墩号", new Date());
        TestUser user3 = new TestUser("刘超琪", false, "刘家墩五号", new Date());
        TestUser user4 = new TestUser("刘亮", true, "刘家墩号", new Date());
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);
        boolean b = testUserService.saveBatch(list);
        return R.ok(b);
    }

    /**
     * 通过删除一个用户
     *
     * @param id
     * @return
     */
    @DeleteMapping("/deleteOne/{id}")
    public R<Boolean> removeUser(@PathVariable Integer id) {
        boolean remove = testUserService.removeById(id);
        return R.ok(remove);
    }

    /**
     * 批量删除指定id的数据
     *
     * @param 
     * @return
     */
    @DeleteMapping("/deleteMore/{ids}")
    public R<Boolean> deleteBatch(@PathVariable("ids") Integer... ids) {

        List<Integer> list = Arrays.asList(ids);
        boolean batch = testUserService.removeBatchByIds(list);
        return R.ok(batch);
    }

    /**
     * 更新指定id的信息
     *
     * @param id
     * @return
     */
    @PostMapping("/updateOne/{id}")
    public R<Boolean> updateOne(@RequestParam Integer id) {
        TestUser user = new TestUser(id);
        user.setName("张三").setSex(false).setAddress("北京朝阳路5号").setCreateTime(new Date());
        boolean b = testUserService.updateById(user);
        return R.ok(b);
    }

    /**
     * 查找指定id信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getOne/{id}")
    public R<TestUser> selectOne(@PathVariable Integer id) {
        TestUser user = testUserService.getById(id);
        return R.ok(user);
    }

    /**
     * 返回所有数据
     *
     * @return
     */
    @GetMapping("/getAll")
    public R<List<TestUser>> getAll() {
        return R.ok(testUserService.list());
    }

    /**
     * 查找多条消息
     *
     * @param ids
     * @return
     */
    @GetMapping("/getMore/{ids}")
    public R<List<TestUser>> selectMore(@PathVariable Integer... ids) {
        List<TestUser> testUsers = testUserService.listByIds(Arrays.asList(ids));
        return R.ok(testUsers);
    }

    /**
     * 查询name中包含inName，sex为inSex的信息，并只返回id，name，sex
     *
     * @param inName 输入的name
     * @param inSex  输入的sex
     * @return
     */
    @GetMapping("/likeSelect/{num}/{sex}")
    public R<List<TestUser>> likeSelect(@PathVariable("num") Integer inName, @PathVariable("sex") Boolean inSex) {
        QueryWrapper<TestUser> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name", "sex").like("name", inName).in("sex", inSex);
        List<TestUser> list = testUserService.list(wrapper);
        return R.ok(list);
    }

    /**
     * 返回地址中包含的数字并且输入id大于一定数或者createTime为空的数据
     *
     * @param inId    指定id
     * @param address 地址包含的数
     * @return
     */
    @GetMapping("getLike/{id}/{num}")
    public R<List<TestUser>> getLike(@PathVariable("id") Integer inId, @PathVariable("num") Integer address) {
        QueryWrapper<TestUser> wrapper = new QueryWrapper<>();
        wrapper.like("address", address).and(wq -> wq.isNull("createTime").or().ge("id", inId));
        return R.ok(testUserService.list(wrapper));
    }

    /**
     * 多条件匹配
     *
     * @param objName 输入指定的名字
     * @param sex     输入指定的性别
     * @return
     */
    @GetMapping("/AllEq/{name}/{sex}")
    public R<List<TestUser>> allEq(@PathVariable("name") Object objName, @PathVariable("sex") Boolean sex) {
        QueryWrapper<TestUser> wrapper = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        map.put("name", objName);
        map.put("sex", sex);
        wrapper.allEq(map);
        return R.ok(testUserService.list(wrapper));
    }

    /**
     * 把查询条件按map形式展现出来
     *
     * @param mName 输入指定的名字
     * @param mSex  输入指定的性别
     * @return
     */
    @GetMapping("/map/{name}/{sex}")
    public R<List<Map<String, Object>>> map(@PathVariable("name") Object mName, @PathVariable("sex") Boolean mSex) {
        QueryWrapper<TestUser> wrapper = new QueryWrapper<>();
        wrapper.like("name", mName).in("sex", mSex);
        System.out.println("maps测试如下：" + "\n");
        List<Map<String, Object>> maps = testUserService.listMaps(wrapper);
        maps.forEach(System.out::println);
        return R.ok(maps);
    }

    /**
     * objs测试
     * @param name
     * @param address
     * @return 符合条件的id集合
     */
    @GetMapping("/objs/{name}/{address}")
    public R<List<Object>> objs(@PathVariable("name") Object name, @PathVariable("address") Object address) {
        QueryWrapper<TestUser> wrapper = new QueryWrapper<>();
        wrapper.like("name", name).like("address", address);
        System.out.println("objs测试如下：" + "\n");
        List<Object> objects = testUserService.listObjs(wrapper);
        objects.forEach(System.out::println);
        return R.ok(objects);
    }

    /**
     * lambda测试
     *
     * @param sex     指定性别
     * @param address 指定地址
     * @return
     */
    @GetMapping("/lambda/{sex}/{address}")
    public R<List<TestUser>> lambdaTest(@PathVariable Boolean sex, @PathVariable Object address) {
        LambdaQueryWrapper<TestUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(TestUser::getSex, sex).like(TestUser::getAddress, address);
        System.out.println("lambda测试如下：" + "\n");
        List<TestUser> lambda = testUserService.list(lambdaQueryWrapper);
        lambda.forEach(System.out::println);
        return R.ok(lambda);
    }

    /**
     * lambda链式测试 ：需要注入TestUserDao，基本mapper接口
     * @param name 输入name
     * @param address 输入address
     * @return
     */
    @GetMapping("/lambdaChain/{name}/{address}")
    public R<List<TestUser>> chain(@PathVariable Object name, @PathVariable Object address) {
        List<TestUser> chain = new LambdaQueryChainWrapper<TestUser>(Mapper)
                .like(TestUser::getName, name).like(TestUser::getAddress, address).list();
        System.out.println("lambda链式测试："+"\n");
        chain.forEach(System.out::println);
        return R.ok(chain);
    }

    /**
     * 分页
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Map<String,Object>> method(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize){
        Page<TestUser> page = new Page<>(pageNum, pageSize);
        //利用mapper接口类对象获取页面
        List<TestUser> data = Mapper.selectPage(page, null).getRecords();
        //获取总数
        long total = page.getTotal();
        Map<String, Object> map = new HashMap<>();
        map.put("data",data);
        map.put("total",total);
        Set<Map.Entry<String, Object>> entries = map.entrySet();
        entries.forEach(System.out::println);
        return R.ok(map);
    }
    
/*                            前后端分离测试                    */

    /**
     * 添加用户
     *
     * @param request
     * @return
     */
    @PostMapping("/addUserTo")
    public R<Object> addUser(HttpServletRequest request) {
        JSONObject object = new JSONObject();
        String name = request.getParameter("name").trim();
        String sex = request.getParameter("sex").trim();
        String address = request.getParameter("address").trim();
        String createTime = request.getParameter("createTime").trim();
        if ("".equals(name)) {
            object.put("code", 0);
            object.put("msg", "用户不能为空");
            return R.ok(object);
        }
        TestUser user = new TestUser();
        Date date = new Date();
        try {
            date = dataFormat.parse(createTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        user.setName(name);
        user.setSex(Boolean.valueOf(sex));
        user.setAddress(address);
        user.setCreateTime(date);
        try {
            boolean add = testUserService.save(user);
           
            if (add) {
                object.put("code", 1);
                object.put("success", true);
                object.put("msg", "添加成功");
                object.put("type", "success");
                return R.ok(object);
            } else {
                object.put("code", 0);
                object.put("success", false);
                object.put("msg", "添加失败");
                object.put("type", "error");
                return R.buildFailure(ResponseEnum.FAIL.getCode(), ResponseEnum.FAIL.getResultMessage());
            }
        } catch (DuplicateKeyException e) {
            object.put("code", 2);
            object.put("success", false);
            object.put("msg", "用户已存在");
            object.put("type", "error");
            return R.buildFailure(ResponseEnum.MSG_ERROR.getCode(), ResponseEnum.MSG_ERROR.getResultMessage());
        }
    }

    /**
     * 前端获取所有数据
     *
     * @return
     */
    @GetMapping("/getAllTo")
    public R<List<TestUser>> allUser() {
        return R.ok(testUserService.list());
    }

    /**
     * 返回指定id的用户
     *
     * @param request
     * @return
     */
    @GetMapping("/getById")
    public R<TestUser> getById(HttpServletRequest request) {
        String id = request.getParameter("id");
        TestUser user = testUserService.getById(id);
        return R.ok(user);
    }

    /**
     * 删除用户
     *
     * @param request
     * @return
     */
    @DeleteMapping("deleteUserTo")
    public R<Boolean> deleteUserTo(HttpServletRequest request) {
        String id = request.getParameter("id");
        return R.ok(testUserService.removeById(id));
    }

    /**
     * 更新用户信息
     *
     * @param request
     * @return
     */
    @PostMapping("/updateUserTo")
    public R<Object> updateUserTo(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        String id = request.getParameter("id").trim();
        String name = request.getParameter("name").trim();
        String sex = request.getParameter("sex").trim();
        String address = request.getParameter("address").trim();
        String createTime = request.getParameter("createTime").trim();
        TestUser testUser = new TestUser();
        Date date = new Date();
        try {
            date = dataFormat.parse(createTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        testUser.setId(Integer.parseInt(id));
        testUser.setName(name);
        testUser.setSex(Boolean.valueOf(sex));
        testUser.setAddress(address);
        testUser.setCreateTime(date);
        boolean res = testUserService.updateById(testUser);
        if (res) {
            jsonObject.put("code", 1);
            jsonObject.put("msg", "修改成功！");
             R.ok(jsonObject).toString();
            return R.ok(jsonObject);
        } else {
            jsonObject.put("code", 0);
            jsonObject.put("msg", "修改失败");
            return R.buildFailure(ResponseEnum.FAIL.getCode(), ResponseEnum.FAIL.getResultMessage());
        }
    }
}
